import subprocess
import numpy as np
import cv2
import datetime
import os

mumu_host = '127.0.0.1'
mumu_port = 16384
adb_path = os.path.join(os.getcwd(), "resource", "platform-tools", "adb.exe")
def launch_app():
    """
    执行 adb 启动应用操作
    :return: 驱动结果（bool）
    """
    now = datetime.datetime.now()
    formatted_time = now.strftime("%H:%M:%S")
    # 连接 MuMu
    subprocess.run(f"{adb_path} connect {mumu_host}:{mumu_port}", shell=True, capture_output=True)
    package_name = "com.papegames.lysk.cn"
    launch_activity = "com.paper.x3sdk.X3UnityPlayerActivityForPaperSDK"
    command = f"{adb_path} shell am start -n {package_name}/{launch_activity}"
    try:
        subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        print(f"恋与深空，启动！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"启动应用失败，错误信息：{e.stderr}")
        return False
    
def get_mumu_screenshot_as_cv2():
    """
    通过 adb 截屏并返回 OpenCV (numpy.ndarray) 格式
    """
    # 获取截屏二进制数据
    result = subprocess.run(
        f"{adb_path} exec-out screencap -p",
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    if result.returncode != 0:
        raise RuntimeError(f"ADB 截屏失败: {result.stderr.decode()}")

    # 转换为 numpy 数组 (OpenCV 格式)
    img_array = np.frombuffer(result.stdout, dtype=np.uint8)
    img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
    return img

def perform_adb_tap(x, y):
    """
    执行 adb 点击操作
    :param x: 点击位置的 x 坐标
    :param y: 点击位置的 y 坐标
    """
    command = f"{adb_path} shell input tap {x} {y}"
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise RuntimeError(f"ADB 点击操作失败: {result.stderr.decode()}")

def perform_adb_scroll_to_bottom():
    """
    执行 adb 滑动到底部操作（向下滑）
    """
    # 获取屏幕尺寸
    result = subprocess.run(f"{adb_path} shell wm size", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise RuntimeError(f"获取屏幕尺寸失败: {result.stderr.decode()}")
    output = result.stdout.decode().strip()
    width, height = map(int, output.split(': ')[1].split('x'))

    # 定义滑动起点和终点
    start_x = width // 2
    # 起点的 y 坐标在屏幕上方
    start_y = height * 3 // 4
    end_x = width // 2
    # 终点的 y 坐标在屏幕下方
    end_y = height // 4

    # 执行滑动操作
    command = f"{adb_path} shell input swipe {start_x} {start_y} {end_x} {end_y} 500"
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise RuntimeError(f"ADB 滑动操作失败: {result.stderr.decode()}")

def press_esc():
    """
    执行 adb 模拟按下 ESC 键的操作
    """
    command = f"{adb_path} shell input keyevent 111"
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise RuntimeError(f"ADB 模拟按下 ESC 键操作失败: {result.stderr.decode()}")
    

def perform_adb_scroll(start_x,start_y,end_x,end_y):
    """
    执行 adb 自定义滑动到底部操作（向下滑）
    """
    # 执行滑动操作
    command = f"{adb_path} shell input swipe {start_x} {start_y} {end_x} {end_y} 500"
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        raise RuntimeError(f"ADB 滑动操作失败: {result.stderr.decode()}")